<?php

namespace AppVue\Http\Controllers;

use Auth;
use Hash;
use Illuminate\Http\Request;
use Illuminate\Support\Str;
use Validator;

class UserController extends Controller
{
    public function changePassword(Request $request)
    {
        if ($request->method() === 'GET') {
            return view('user.change_password');
        } else {
            $validator = Validator::make($request->all(), [
                'old_password' => 'required|string|min:4',
                'password' => 'required|string|min:4|confirmed',
            ]);

            if ($validator->fails()) {
                return redirect('/change/password')
                    ->withInput($request->all())
                    ->withErrors($validator->getMessageBag()->getMessages());
            }
            if (Hash::check($request->get('old_password'), Auth::user()->password)) {
                $user  = Auth::user();
                $user->password = bcrypt($request->get('password'));
                $user->remember_token = Str::random(32);
                $user->save();
                return redirect('/change/password')->with('success', 'Change Success');
            } else {
                return redirect('/change/password')
                    ->with('error', 'Change Fail')
                    ->withInput($request->all())
                    ->withErrors(['old_password'=> ['The old password is incorrect']]);
            }
        }
    }
}
